<?php defined('BASEPATH') or exit('No direct script access allowed');
/**
 * Public Channel module controller
 *
 * @author  PyroCMS Dev Team
 * @package PyroCMS\Core\Modules\Blog\Controllers
 */
class Channel extends L_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('bet_type_m');
		$this->load->model('channel_m');
		$this->load->model('transaction_m');
		$this->load->model('l_user_m');
		
		$this->load->library('liberty_reserver');
    	
		$user_id = $this->session->userdata('id');
		if (!empty($user_id)) {
	    	$balance_amount = $this->l_user_m->get_account_balance($user_id);
			$this->template->set('balance_amount', $balance_amount);
		}
		
		$this->template
			 ->set('redirect_to', "")
			 ->set_partial('header', 'partials/header')
			 ->set_partial('right_panel', 'partials/right_panel');
	}

	public function index()
	{
		if (isset($_REQUEST['ct']) && in_array($_REQUEST['ct'], array('MB', 'MN', 'MT'))) {
			$channel_type = $_REQUEST['ct'];
		}
		if (!isset($channel_type)) {
			if (isset($_SESSION['SELECTED_CHANNEL_TYPE'])) {
				$channel_type = $_SESSION['SELECTED_CHANNEL_TYPE'];
			} else {
				$channel_type = 'MN';
			}
		}
		$_SESSION['SELECTED_CHANNEL_TYPE'] = $channel_type;
		
		// Check post and session for the redirect place
		$redirect_to = ($this->input->post('redirect_to')) 
			? trim(urldecode($this->input->post('redirect_to')))
			: $this->session->userdata('redirect_to');

		// Any idea where we are heading after login?
		if ( ! $_POST and $args = func_get_args())
		{
			$this->session->set_userdata('redirect_to', $redirect_to = implode('/', $args));
		}
		$bet_types = $this->bet_type_m->find_by_channel_type_with_cache($channel_type);
		foreach ($bet_types as $i => $bet_type) {
			$partial_resource = 'partials/bet_types/' . $bet_type->channel_type. '/' . str_replace('.', '_', $bet_type->bet_type);
			$partial_file = $_SERVER['DOCUMENT_ROOT'] . '/addons/default/modules/channel/views/' . $partial_resource. '.php';
			if (file_exists($partial_file)) {
				$this->template->set_partial('bet_type_'.$bet_type->id, $partial_resource);
			}
		}
		
		$today_channels = $this->channel_m->find_today_channels_by_channel_type($channel_type);
		
		$close_times = $this->channel_m->find_today_close_time_by_channel_type($channel_type);
		
		$this->template
			 ->set('redirect_to', $redirect_to)
			 ->set('bet_types', $bet_types)
			 ->set('today_channels', $today_channels)
			 ->set('start_close_time', date('Y-m-d\\TH:i:s', $close_times[0]))
			 ->build('index');
	}
	
	public function deposit() {
		if (!$this->ion_auth->logged_in()) {
			redirect('users/login');
			return;
		}
		
		$this->template
			 ->build('credit/deposit');
	}
	
		/**
	 * 
	 * After Liberty Reserver finish processing the transfer request, 
	 * a callback url will be triggered. 
	 * This method is the handler of callback url.
	 */
	public function deposit_success() {
		Events::trigger('deposit');
		$balance_amount = $this->l_user_m->get_account_balance($this->current_user->id);
		$this->template
				 ->set('balance_amount', $balance_amount)
			 	 ->build('credit/deposit_success');
	}
	
	public function deposit_fail() {
		Events::trigger('deposit');
		$this->template
			 	 ->build('credit/deposit_failed');
	}
	
	public function withdraw() {
		if (!$this->ion_auth->logged_in()) {
			redirect('users/login');
			return;
		}
		$this->template
			 ->build('credit/withdraw');
	}
	
	public function process_withdraw() {
		if (!$this->ion_auth->logged_in()) {
			redirect('users/login');
			return;
		}
		$errors = array();
		$lr_payee_acc = $_REQUEST['lr_payee_acc'];
		$amount = $_REQUEST['amount'];
		$balance_amount = $this->l_user_m->get_account_balance($this->current_user->id);
		$now=new DateTime();
		if ($balance_amount >= $amount) {
			$result = $this->liberty_reserver->transfer($lr_payee_acc, $amount);
			
			$this->transaction_m->withdraw($this->current_user->id, $amount);
			
			$balance_amount = $this->l_user_m->get_account_balance($this->current_user->id);
			Events::trigger('lr_acc_change', $_REQUEST['lr_payee_acc']);
			$this->template
				 ->set('balance_amount', $balance_amount)
			 	 ->build('credit/withdraw_success');
		} else {
			$errors[] = 'Số tiền muốn rút ('.$amount.'LR) lớn hơn số dư hiện tại ('.number_format($balance_amount, 2).'LR)';
			$this->template
				 ->set('errors', $errors)
			 	 ->build('credit/withdraw_failed');
		}
	}
	
	public function deposit_status() {
		$lr_config = $this->config->item('liberty_reserver');
		$str = 
		  $_REQUEST["lr_paidto"].":".
		  $_REQUEST["lr_paidby"].":".
		  stripslashes($_REQUEST["lr_store"]).":".
		  $_REQUEST["lr_amnt"].":".
		  $_REQUEST["lr_transfer"].":".
		  $_REQUEST["lr_currency"].":".
		  $lr_config["lr_store_security_word"];
		  
		//Calculating hash
		$hash = strtoupper(hash('SHA256', $str));  
		
		
		//Let's check that all parameters exist and match and that the hash 
		//string we computed matches the hash string that was sent by LR system.
		if (isset($_REQUEST["lr_paidto"]) &&  
		    $_REQUEST["lr_paidto"] == strtoupper($lr_config['lr_store_acc']) &&
		    isset($_REQUEST["lr_store"]) && 
		    stripslashes($_REQUEST["lr_store"]) == $lr_config['lr_store_name'] &&
		    isset($_REQUEST["lr_encrypted"]) &&
		    $_REQUEST["lr_encrypted"] == $hash &&
		    isset($_REQUEST["lr_currency"]) &&
		    $_REQUEST["lr_currency"] == $lr_config['lr_currency']) {
		    
		    $user_id = $_REQUEST["user_id"];
		    
			$this->transaction_m->deposit($user_id, $_REQUEST['lr_amnt']);
			Events::trigger('lr_acc_change', $_REQUEST["lr_paidby"]);
		} else {
			//suspend this user;
		}
	}
	
	
	
	public function transfer_history () {
		$transfer_histories = $this->report_m->getListDepositWithdraw(null, null, $this->current_user->id);
		$this->template
			 ->set('transfer_histories', $transfer_histories)
				 ->build('report/transfer_history');
	}
	
	public function bet_history() {
		$bet_histories = $this->report_m->getBetListOfAllChannel(null, null, false, $this->current_user->id);
		$this->template
			 ->set("bet_histories", $bet_histories)
			 ->build('report/bet_history');		
	}
}
